/**
 * Fetch服务
 */
import http from '@ohos.net.http';
import { HttpRequestParams } from '../base/HttpRequest';
import { HttpRequestConstants } from '../constants/HttpRequestConstants';
import { LogUtil } from '../utils/LogUtil';
export class FetchService {

  async get<T>(): Promise<T> {
    const response = await this.request(http.RequestMethod.GET);
    if (response.code !== 0) {
      throw new Error(response.msg);
    }
    const data: T = await response.data;
    return data;
  }

  async post<T>(body: HttpRequestParams): Promise<T> {
    const response = await this.request(http.RequestMethod.POST, body);
    const result = JSON.parse(response);
    if (result.code !== 0) {
      throw new Error(result.msg);
    }
    const data: T = await result;
    return data;
  }

  private async request(method: http.RequestMethod, body?: HttpRequestParams): Promise<any> {
    return new Promise((resolve, reject) => {
      let httpReq = http.createHttp();
      httpReq.request(HttpRequestConstants.BASE_URl, {
        method: method,
        extraData: body
      }).then((ret) => {
        LogUtil.info(`httpResult: ${JSON.stringify(ret)}`);
        if(ret.responseCode === http.ResponseCode.OK) {
          LogUtil.info(`apiResult: ${JSON.stringify(ret.result)}`);
          resolve(ret.result)
        }
      }).catch((err) => {
        LogUtil.error(`httpError: ${JSON.stringify(err)}`);
        reject(err);
      })
    });
  }
}
